"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root :
            return root
        root.next=None
        root1=root
        while root1.left:
            root2=root1
            while root2:
                root2.left.next=root2.right
                if root2.next:
                    root2.right.next=root2.next.left
                root2 = root2.next
            root1 = root1.left
        return root